# --- Setup ---
rm(list = ls())
setwd("/Users/John/Dropbox/")

# --- Load Required Packages
library(readr)
library(interflex)
library(tidyverse)
library(ggplot2)
library(cowplot)

# --- Load Dataset ---

df <- as.data.frame(read_csv("JOP_Replication_Materials/appendix/data/final_dataset_rnd_only.csv"))

# --- Interflex Model ---
intflex <- df %>%
  dplyr::select(isic, isic2, year, strategic, sqrtta, isic_year, median_share, 
                med_hhi_isic2, med_soe_isic2) %>%
  mutate(Strategic = strategic)

intflex <- as.data.frame(intflex)

# --- Poisson Model ---
bin.p <- interflex(estimator = "binning", Y = "isic_year", D = "Strategic", X = "median_share", 
                   Z = c("med_hhi_isic2", "med_soe_isic2"),
                   data = intflex, vcov.type = "cluster", cl = "isic", 
                   na.rm = TRUE, main = "Marginal Effect of Strategic Status \n R&D-Intensive Industries Only (Poisson)", Ylabel = "Tech Absorption", 
                   Xlabel = "Median Processing Share", method = "poisson",
                   cex.main = 1, ncols = 1, theme.bw = TRUE, nbins = 3, bin.labs = F)

# --- Linear Model ---
bin.l <- interflex(estimator = "binning", Y = "sqrtta", D = "Strategic", X = "median_share", 
                   Z = c("med_hhi_isic2", "med_soe_isic2"),
                   data = intflex, vcov.type = "cluster", cl = "isic", 
                   na.rm = TRUE, main = "Marginal Effect of Strategic Status \n R&D-Intensive Industries Only (Linear)", Ylabel = "Tech Absorption", 
                   Xlabel = "Median Processing Share", method = "linear",
                   cex.main = 1, ncols = 1, theme.bw = TRUE, nbins = 3, bin.labs = F)

# --- Extract figures from interflex models ---
fig_bin_p <- bin.p$figure  # Poisson plot
fig_bin_l <- bin.l$figure  # Linear plot

# --- Combine the plots side-by-side using plot_grid from cowplot ---
combined_figure <- plot_grid(fig_bin_p, fig_bin_l, labels = NULL, nrow = 1, align = "v")

# --- Save the combined figure ---
plot_path <-"JOP_Replication_Materials/appendix/output/C_figure_4.pdf"
ggsave(plot_path, combined_figure, width = 14, height = 6)

message("✅ Saved combined figure to: ", plot_path)
browseURL(plot_path)